<template>
  <div id="sub-items-echarts" :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from '../mixins/resize'

var points = [
  {
    name: "OCV测试\n ocv test",
    value: [300, 450],
    /*target: ['工序2'],*/

  },
  {
    name: "电芯堆叠\n cell stacking",
    value: [600, 450],
    /*target: ['工序3'],*/
  },
  {
    name: "挤压整形\n extrusion moulding",
    value: [900, 450],
    /*target: ['工序4'],*/
  }, {
    name: "焊前寻址\n addresing before \n welding",
    value: [900, 300],
   /* target: ['工序5'],*/
  }, {
    name: "CCS安装\n ccs install",
    value: [600, 300],
   /* target: ['工序6']*/
  }, {
    name: "激光焊接\n laser welding",
    value: [300, 300],
    /*target: ['工序7']*/
  }, {
    name: "焊后检测\n after welding \n inspection",
    value: [0, 300],
  /*  target: ['工序8']*/
  }, {
    name: "EOL测试\n eol test",
    value: [0, 100],
    /*target: ['工序9','工序10']*/
  }, {
    name: "安装上盖\n install the cover",
    value: [300, 170],
    /*target: ['工序11']*/
  }, {
    name: "底部绝缘片\n bottom insulating\n sheet",
    value: [300, 50],
    /*target: ['工序11']*/
  }, {
    name: "模组下线\n module offline",
    value: [600, 100],

  }];
/*
   获取target在source中的坐标
   */
var getPointCoordinate = function (source, targetName) {
  var targetItem = source.filter(item => {
    return item.name == targetName;
  });
  console.log('targetItem,', targetItem);
  return targetItem[0].value;
}

/*
获取路径要添加的点
*/
var getRoutePoint = function (startCoordinate, endPointName) {
  var endPoint = getPointCoordinate(points, endPointName);
  var gap = 100;
  var rs = [];
  let startPointX = startCoordinate[0];
  let startPointY = startCoordinate[1];
  let endPointX = endPoint[0];
  let endPointY = endPoint[1];
  //横坐标相同
  if (startPointX == endPointX) {
    var point1 = {
      name: 'offset1' + endPointName,
      value: [startPointX + gap, startPointY],
      symbol: 'none',
      target: ['offset2' + endPointName]
    };
    var point2 = {
      name: 'offset2' + endPointName,
      value: [startPointX + gap, endPointY],
      symbol: 'none',
      target: [endPointName]
    };
    rs.push(point1);
    rs.push(point2);
  } else if (startPointY == endPointY) {
    var point1 = {
      name: 'offset1' + endPointName,
      value: [startPointX, startPointY - gap],
      symbol: 'none',
      target: ['offset2' + endPointName]
    };
    var point2 = {
      name: 'offset2' + endPointName,
      value: [endPointX, startPointY - gap],
      symbol: 'none',
      target: [endPointName]
    };
    rs.push(point1);
    rs.push(point2);
  } else {
    rs.push({
      name: 'offset1' + endPointName,
      value: [endPointX, startPointY],
      symbol: 'none',
      target: [endPointName]
    });
  }
  return rs;
}

var handlePoints = function (points) {

  for (var i = 0; i < points.length; i++) {
    var item = points[i];
    //当前点坐标
    var currentCoordinate = item.value;
    //是否存在目标点连线
    if (item.target) {
      var targetItem = item.target;
      for (var j = 0; j < targetItem.length; j++) {
        var selected = item.selected;
        //是否需要偏移偏移需要虚拟点
        if (item.offset) {
          var routes = getRoutePoint(currentCoordinate, targetItem[j]);
          var newTarget = [routes[0].name]
          item.target = newTarget;
          for (const key in routes) {
            var element = routes[key];
            element.selected = selected;
            points.push(element)
          }
        }
      }
    }
  }
  return points;
}

var newPoints = handlePoints(points);

console.log('newPoints', newPoints)

var linesData = function (points) {

  return [{
    coords: [
      [440, 450],
      [515, 450]
    ],
  },{
    coords: [
      [740, 450],
      [815, 450]
    ],
  },{
    coords: [
      [920, 390],
      [920, 360]
    ],
  },{
    coords: [
      [815, 300],
      [740, 300]
    ],
  },{
    coords: [
      [515, 300],
      [440, 300]
    ],
  },{
    coords: [
      [215, 300],
      [140, 300]
    ],
  },{
    coords: [
      [20, 235],
      [20, 165]
    ],
  },{
    coords: [
      [140, 115],
      [215, 170]
    ],
  },{
    coords: [
      [140, 85],
      [215, 50]
    ],
  },{
    coords: [
      [440, 170],
      [515, 110]
    ],
  },{
    coords: [
      [440, 50],
      [515, 95]
    ],
  }]
}

var seriesData = function (data) {
  return data.map(item => ({
    name: item.name,
    symbol: item.symbol && item.symbol === 'none' ? 'none' : 'rect',
    symbolSize: item.name.indexOf('offset') != -1 ? 0 : [120, 45], //图标大小
    draggable: false,
    fixed: true,
    value: item.value,
    edgeSymbol: ['circle', 'arrow'],
    itemStyle: {
      normal: {
        color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [{
          offset: 0,
          color: 'rgba(21,126,255,0.1)'
        },
          {
            offset: 1,
            color: 'rgba(53,194,255,0.1)'
          }
        ]),
        borderColor: '#b4b320',
        borderWidth: 1,
      }
    }
  }));
}
console.log('seriesData', seriesData(newPoints))



var links = function (data) {
  console.log('links data', data)
  var res = [];
  for (var i = 0; i < data.length; i++) {
    var item = data[i];
    var currentCoordinate = item.value;
    console.debug('currentCoordinate', currentCoordinate)
    if (item.target) {
      console.debug('item.target', item.target)
      for (var j = 0; j < item.target.length; j++) {
        res.push({
          source: item.name,
          target: item.target[j],
          lineStyle: {
            normal: {
              color: "#b4b320",
            }
          }
        })
      }
    }

  }
  console.log('links', res)

  return res;
}

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '260px'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    chartData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      chart: null,
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      //修改图表高度
      this.height = (document.getElementsByClassName('station')[0].offsetHeight - 0 ) + 'px';
      this.chart = echarts.init(this.$el, 'macarons');
      this.setOptions(this.chartData);
      window.addEventListener('resize', () =>{
        if (this.chart) {
          let fatherHeight = document.getElementsByClassName('station')[0].offsetHeight - 0
          this.height = fatherHeight + 'px';
          this.chart.resize();
        }
      })
    },
    setOptions(data) {
      this.chart.setOption({
        grid:{
          left: '9%',
          right: '5%',
          top: '2%',
          bottom: '10%',
        },
        roam: true,
        xAxis: {
          show: false,
          type: "value"
        },
        yAxis: {
          show: false,
          type: "value"
        },
        tooltip: {},
        series: [{
          type: "graph",
          // zlevel: 5,

          draggable: false,
          coordinateSystem: "cartesian2d", //使用二维的直角坐标系（也称笛卡尔坐标系）

          // edgeSymbolSize: [0, 8], //边两端的标记大小，可以是一个数组分别指定两端，也可以是单个统一指定
          // edgeLabel: {
          //   normal: {
          //     textStyle: {
          //       fontSize: 60
          //     }
          //   }
          // },
          edgeSymbol: ['circle', 'arrow'],
          edgeSymbolSize: [2, 6],

          //关系图节点标记的图形
          symbol: "rect",
          symbolOffset: ['15%', 0],
          label: {
            normal: {
              show: true
            }
          },
          lineStyle: {
            normal: {
              opacity: 1,
              // color: "#cccccc",
              curveness: 0,
              // 12b5d0
              type: "dashed",
              width: 1
            }
          },
          data: seriesData(newPoints),
          links: links(newPoints)

        },
          {
            type: "lines",
            coordinateSystem: "cartesian2d",
            z: 1,
            zlevel: 2,
            animation: false,
            effect: {
              show: true,
              period: 5,
              trailLength: 0.01,
              symbolSize: 6,
              symbol: "arrow",
              loop: true,
              color: "rgba(180,179,32,0.5)"
            },
            lineStyle: {
              curveness: 0,
              color: '#b4b320',
              opacity: 0.6,
              width: 1,
              type: "solid"
            },
            data: linesData()
          }

        ]
      })
    }
  }
}
</script>
